<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * Metas组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Metas_List extends Widget_Abstract_Metas
{
    /**
     * 执行函数,初始化数据
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        $this->parameter->setDefault('field=*&orderSort&orderColumn=mid');	
		
		$pass = false;
		$select = $this->db->select($this->parameter->field)
		    ->from('table.metas');
		
		if($this->parameter->type) { 
		    $select->where('type = ?', $this->parameter->type);
			$pass = true;
		}
		
        if ($this->parameter->name) {
            $select->where('name = ?', $this->parameter->name);
			$pass = true;
        }
		
		if($this->parameter->alias){ 
		    $select->where('alias = ?', $this->parameter->alias);
			$pass = true;
		}
		
		if($this->parameter->mid){
			if(FALSE !== strpos($this->parameter->mid, ',')){ 
	            $midList = array_filter(explode(',', $this->parameter->mid), function($val){
	                return is_numeric($val);
	            });
				if($midList){ 
				    $select->where('mid IN ('.substr( str_repeat( '?,', count( $midList ) ), 0, - 1 ).')', $midList);
				    $pass = true;
				} else {
				    $pass = false;
			    }
			}else{
		        $select->where('mid = ?', $this->parameter->mid);
				$pass = true;
			}
		}

        if ($this->parameter->limit > 0) {
            $select->limit($this->parameter->limit);
        }
		
        if ($this->parameter->offset > 0) {
            $select->offset($this->parameter->offset);
        }
		
        if($pass){
			if(isset($midList)){
			    $list = Common::arrayChangeKey($select->fetchAll(), 'mid');
                foreach ($midList as $v) {
                    isset($list[$v]) && $this->push($list[$v]);
                }
			} else {
			    if($this->parameter->orderSort){
				    $select->order('table.metas.' . $this->parameter->orderColumn, $this->parameter->orderSort);
			    } 
				$select->fetchAll(array($this, 'push'));
			}
        }
    }
}
